/*
 * Copyright (c) 2003-2009 UTRAFE. All rights reserved.
 */

package mz.co.framework.context;

import mz.co.framework.error.ISystemException;
import mz.co.framework.error.SystemException;

/**
 * Holder for UserContext.
 * 
 * @author Tiago da Fonseca Frazao
 */
public class UserContextHolder {
	private static InheritableThreadLocal<IUserContext> contexts = new InheritableThreadLocal<IUserContext>();

	public static void setContext(IUserContext context) {
		contexts.set(context);
	}

	public static void removeContext() {
		contexts.remove();
	}

	public static boolean contextBound() {
		return contexts.get() != null;
	}

	public static IUserContext getContext() throws SystemException {
		IUserContext context = (IUserContext) contexts.get();

		if (context == null) {
			throw new SystemException(ISystemException.CONTEXT_NOT_FOUND);
		}

		return context;
	}

	public static IUserContext getStubContext() throws SystemException {
		return new IUserContext() {
			@Override
			public Long getId() {
				return Long.valueOf(1);
			}

			@Override
			public String getIp() {
				return "127.0.0.1";
			}
		};
	}

}
